import {
  editArticleApi,
  getArticleById,
  getLabel,
  getPrivateLabel,
  publishArticle,
  upLoadImage,
} from '@/services/articles/index';
import type { RequestOptionsType } from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormCheckbox,
  ProFormDependency,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { Button, Col, Form, Input, message, Row } from 'antd';
import { MdEditor } from 'md-editor-rt';
import React, { useEffect, useState } from 'react';
import { useParams } from 'umi';
// import ReadExtension from '@/components/ReadExtension';
import TimeNow from '@/components/TimeNow';
import type { ArticleStateTypeI } from '@/constant/article';
import articleEnum from '@/constant/article';
import useRequest from '@ahooksjs/use-request';
import { SafetyCertificateFilled } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';
import type { RcFile, UploadChangeParam } from 'antd/lib/upload';
import { uniqBy } from 'lodash';
import styles from './index.less';

const editorId = 'editor-preview';
interface FormType {
  articleType: string;
  articleCover: string;
  articleIsOverhead: string;
  recommend: string;
  articleSummary: string;
  articleLabel: RequestOptionsType[];
}
interface ArticleCoverDataSourceT {
  articleCoverFile: string[];
}
const { articleType } = articleEnum;
const ArticleAdd: React.FC = () => {
  const [title, setTitle] = useState<string>();
  const [content, setContent] = useState<string>('');
  const [formRef] = Form.useForm<FormType>();
  const [open, setOpen] = useState(false);
  // 发布文章或者保存草稿 0 草稿 1 发布
  const [articleState, setArticleState] = useState<keyof ArticleStateTypeI>(1);
  const [articleSource, setArticleSource] = useState<ARTICLEAPI.ARTICLE>();
  // 文章封面
  const [articleCoverDataSource, setArticleCoverDataSource] = useState<ArticleCoverDataSourceT>({
    articleCoverFile: [],
  });
  const [articleLabel, setArticleLabel] = useState<
    {
      label: string;
      value: number;
    }[]
  >([]);

  const [isOriginal, setIsOriginal] = useState<boolean>(true);

  const { run: getArticleByIdRun } = useRequest(getArticleById, {
    manual: true,
    onSuccess(data) {
      const {
        code,
        data: { articleContent = '', articleTitle },
        data: dataSource,
        message: errorMessage,
      } = data;
      if (code === 200) {
        setArticleSource(dataSource);
        setContent(articleContent);
        setTitle(articleTitle);
      } else {
        message.error(errorMessage);
      }
    },
  });
  const urlParams = useParams<{ id: string }>();
  // 图片上传
  const upLoadImgHandler = async (files: File[], callBack: (urls: string[]) => void) => {
    console.log(files);
    const { code, data, message: errorMessage } = await upLoadImage({ fileImage: files[0] });
    if (code === 200) {
      callBack([data]);
    } else {
      message.error(errorMessage);
    }
  };

  const finishHandler = async (values: FormType) => {
    if (!title || !title.trim()) {
      message.error('标题不能为空!');
      return false;
    }
    console.log(values);
    const al = values.articleLabel?.map((item) => {
      return item.value as number;
    });
    let res: COMMON.BaseSuccess;
    const requestParams: ARTICLEAPI.AublishArticle = {
      articleContent: content,
      articleTitle: title,
      ...values,
      articleLabel: al,
      articleState,
      articleCover: articleCoverDataSource.articleCoverFile[0],
    };
    if (urlParams.id) {
      requestParams.articleId = urlParams.id;
      // 编辑
      res = await editArticleApi(requestParams);
    } else {
      // 新增
      res = await publishArticle(requestParams);
    }
    message.success(res.data);
    setOpen(false);
    return false;
  };

  // 文章封面上传
  const articleCoverChange: UploadProps['onChange'] = async (
    info: UploadChangeParam<UploadFile>,
  ) => {
    const { fileList, file: { status } = {} } = info;
    if (status === 'uploading') {
      return false;
    }
    if (status === 'done') {
      const {
        code,
        data,
        message: errMsg,
      } = await upLoadImage({
        fileImage: fileList[0].originFileObj as File,
      });
      if (code !== 200) return message.error(errMsg);
      setArticleCoverDataSource({
        articleCoverFile: [data],
      });
    }
  };

  // 获取标签列表
  const getLabelList = async () => {
    const { code, data = [], message: errorMessage } = await getLabel({});
    const { code: pCode, data: pData = [], message: pMessage } = await getPrivateLabel({});
    if (code !== 200 || pCode !== 200) {
      message.error(errorMessage || pMessage);
      return [];
    }
    // 去重
    const newDataList = uniqBy([...data, ...pData], 'articleLabelId');
    const options = newDataList.map((item) => {
      return { label: item.articleLabelName, value: item.articleLabelId };
    });
    setArticleLabel(options);
    return options;
  };

  const valuesChange = (changedValues: any, allValues: FormType) => {
    console.log(allValues);
    setIsOriginal(![1, 2].includes(allValues.articleType as unknown as number));
  };

  useEffect(() => {
    getLabelList();
    if (urlParams.id) {
      // 编辑
      getArticleByIdRun(urlParams.id);
    }
  }, [open]);

  useEffect(() => {
    if (open && articleSource && urlParams.id) {
      // 如果是开启状态并且当前是编辑页面
      const { articleType: articleTypeData, articleLabelList, articleSummary } = articleSource;
      const newArticleLabels = articleLabelList?.map((item) => ({
        label: item.articleLabelName,
        value: item.articleLabelId,
      }));

      formRef.setFieldsValue({
        articleType: articleTypeData,
        articleSummary,
        articleLabel: newArticleLabels,
      });
    }
  }, [articleSource, formRef, open]);

  return (
    <div className={styles.homeWrapper}>
      <div className={styles.row1}>
        <Input
          placeholder="请输入文章标题"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
        <Button
          ghost
          type="primary"
          className={styles.save}
          onClick={() => {
            setOpen(true);
            setArticleState(0);
          }}
        >
          保存草稿
        </Button>
        <Button
          type="primary"
          onClick={() => {
            setOpen(true);
            setArticleState(1);
          }}
        >
          发布文章
        </Button>
      </div>
      <Row className={styles.mdWrap}>
        <Col span={24}>
          <MdEditor
            editorId={editorId}
            onUploadImg={upLoadImgHandler}
            footers={['markdownTotal', '=', 0, 'scrollSwitch']}
            defFooters={[<TimeNow key="time-now" />]}
            className={styles.mdEditorWrapper}
            modelValue={content}
            onChange={(value: string) => setContent(value)}
          />
        </Col>
      </Row>
      <ModalForm<FormType>
        layout="horizontal"
        open={open}
        title="发布文章"
        form={formRef}
        labelAlign="right"
        labelCol={{ flex: '80px' }}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setOpen(false),
        }}
        initialValues={{
          radio: 'a',
          articleType: 0,
          articleLabel: [],
        }}
        onValuesChange={valuesChange}
        submitTimeout={2000}
        onFinish={finishHandler}
      >
        <Row>
          <Col span={14}>
            <ProFormSelect.SearchSelect
              rules={[{ required: true, message: '标签至少选一项' }]}
              mode="multiple"
              options={articleLabel}
              defaultKeyWords=""
              name="articleLabel"
              label="文章标签"
            />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <ProFormUploadButton
              name="articleCover"
              fieldProps={{
                name: 'file',
                listType: 'picture-card',
                onChange: articleCoverChange,
                onPreview: async (file: UploadFile) => {
                  let src = file.url as string;
                  if (!src) {
                    src = await new Promise((resolve) => {
                      const reader = new FileReader();
                      reader.readAsDataURL(file.originFileObj as RcFile);
                      reader.onload = () => resolve(reader.result as string);
                    });
                  }
                  const image = new Image();
                  image.src = src;
                  const imgWindow = window.open(src);
                  imgWindow?.document.write(image.outerHTML);
                },
              }}
              max={1}
              label="封面上传"
            />
          </Col>
        </Row>
        <Row justify="space-between">
          <Col span={22}>
            <ProFormTextArea
              rules={[
                {
                  required: true,
                  message: '文章简介为必填',
                },
                {
                  max: 160,
                  message: '文章简介最多为160字符',
                },
              ]}
              label="文章简介"
              name="articleSummary"
              fieldProps={{
                showCount: true,
                maxLength: 160,
              }}
              style={{ maxWidth: '80%' }}
              placeholder="请输入当前文章简介"
            />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <ProFormRadio.Group
              name="articleType"
              label="文章类型"
              options={articleType.transArray?.map((item: ENUM.BaseType) => {
                let label = item.label;
                if (item.key === 0) {
                  label = (
                    <div>
                      {item.label}
                      <SafetyCertificateFilled style={{ color: '#52c41a', marginLeft: '6px' }} />
                    </div>
                  ) as any;
                }
                return {
                  label,
                  value: item.key,
                };
              })}
            />
          </Col>
          {!isOriginal ? (
            <Col span={12}>
              <ProFormText placeholder="请填写原文链接" name="originUrl" />
              <ProFormCheckbox.Group
                name="authorization"
                layout="vertical"
                options={['原文允许转载或者本次转载已获得原文作者授权']}
              />
            </Col>
          ) : null}
        </Row>
        {/* <Row>
          <Col span={12}>
            <Row gutter={[24, 24]}>
              <Col>
                <ProFormSwitch
                  label="置顶"
                  checkedChildren="1"
                  unCheckedChildren="0"
                  name="articleIsOverhead"
                />
              </Col>
              <Col>
                <ProFormSwitch
                  checkedChildren="1"
                  unCheckedChildren="0"
                  label="推荐"
                  name="recommend"
                />
              </Col>
            </Row>
          </Col>
        </Row> */}

        <Row>
          <Col span={12}>
            <ProFormRadio.Group
              name="radio"
              label="发布形式"
              options={[
                {
                  label: '公开',
                  value: 'a',
                },
                {
                  label: '密码',
                  value: 'b',
                },
              ]}
            />
          </Col>
          <Col span={12}>
            <ProFormDependency name={['radio']}>
              {({ radio }) => {
                if (radio === 'b') {
                  return (
                    <Row>
                      <ProFormText name="pwd" label="密码" />
                    </Row>
                  );
                }
                return null;
              }}
            </ProFormDependency>
          </Col>
        </Row>
      </ModalForm>
    </div>
  );
};

export default ArticleAdd;
